package com.crypt.properties.util;

public class HexBytes {
    public static String toHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(bytes[i] & 0XFF);
            if (hex.length() < 2) {
                sb.append(0);
            }
            sb.append(hex);
        }
        return sb.toString();
    }

    public static byte[] toBytes(String hex) {
        int len = hex.length();
        byte[] bytes;
        if (len % 2 == 1) {
            // 奇数
            len++;
            bytes = new byte[len / 2];
            hex = "0" + hex;
        } else {
            bytes = new byte[len / 2];
        }
        int index = 0;
        for(int i =0 ;i < len;i+=2){
            bytes[index] = (byte) Integer.parseInt(hex.substring(i,i+2), 16);
            index ++ ;
        }
        return bytes;
    }
}
